import fs from 'node:fs';
import path from 'node:path';

const __dirname = process.cwd();
const pkgPath = path.resolve(__dirname, 'package.json');
const pkgContent = fs.readFileSync(pkgPath, 'utf8');
const pkg = JSON.parse(pkgContent);

// 修改 name 字段
if (pkg.name && pkg.name.startsWith('@vben/')) {
  const suffix = pkg.name.split('/').pop();
  pkg.name = `mldong-vben-${suffix}`;
}
if (pkg.name && pkg.name.startsWith('@vben-core/')) {
  const suffix = pkg.name.split('/').pop();
  pkg.name = `mldong-vben-core-${suffix}`;
}

// 设置 private: false
pkg.private = false;

// 获取当前版本号

const version = process.env.M_VERSION || pkg.version;
pkg.version = version;
// 修改 dependencies 中的 @vben/* 为 mldong-vben-*
if (pkg.dependencies) {
  Object.keys(pkg.dependencies).forEach((dep) => {
    if (dep.startsWith('@vben/')) {
      const suffix = dep.split('/').pop();
      const newDepName = `mldong-vben-${suffix}`;
      pkg.dependencies[newDepName] = `^${version}`;
      // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
      delete pkg.dependencies[dep];
    }
    if (dep.startsWith('@vben-core/')) {
      const suffix = dep.split('/').pop();
      const newDepName = `mldong-vben-core-${suffix}`;
      pkg.dependencies[newDepName] = `^${version}`;
      // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
      delete pkg.dependencies[dep];
    }
  });
}

// 写入新文件 package-new.json
const newPkgPath = path.resolve(__dirname, 'package.json.new');
fs.writeFileSync(newPkgPath, JSON.stringify(pkg, null, 2), 'utf8');

console.log('✅ 已成功生成:', newPkgPath);
